//
//  WSQuestionDetailViewController.m
//  WisdomStar
//
//  Created by 谭飞 on 2018/11/1.
//  Copyright © 2018年 zhangliwen. All rights reserved.
//

#import "WSQuestionDetailViewController.h"
#import "WSCommentViewController.h"
#import "WSQuestionDetailHeader.h"
#import "WSQuestionDetailCell.h"

#import "QAService.h"
#import "QuestionDetailInfo.h"

@interface WSQuestionDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) WSQuestionDetailHeader *headerView;

@property (nonatomic, strong) QuestionDetailInfo *detailInfo;
@property (nonatomic, strong) NSArray *datas;

@end

@implementation WSQuestionDetailViewController

#pragma mark - Life cycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    [self setup];
    [self loadData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.headerView.xmg_height = self.headerView.contentHeight;
}

- (void)setup {
    // table view header
    WSQuestionDetailHeader *header = [WSQuestionDetailHeader viewFromXib];
    self.headerView = header;
    self.tableView.tableHeaderView = header;
    self.tableView.tableFooterView = [UIView new];
    
    // regist cells
    [self.tableView registerNib:[UINib nibWithNibName:[WSQuestionDetailCell className] bundle:nil] forCellReuseIdentifier:[WSQuestionDetailCell className]];
}


/**
 加载详情数据
 */
- (void)loadData {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"token"] = User_Token;
    dic[@"id"] = _ask_id;
    [QAService fetchAskDetailsWithParams:dic result:^(id object) {
        ResponseModel *response = [ResponseModel yy_modelWithJSON:object];
        if (!response.data) {
            return;
        }
        self.detailInfo = [QuestionDetailInfo yy_modelWithJSON:response.data];
        self.headerView.detail = self.detailInfo;
        [self.tableView reloadData];
    }];
}

#pragma mark - 发表评论

- (IBAction)addComment:(id)sender {
    WSCommentViewController *commentVc = [[WSCommentViewController alloc] init];
    commentVc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    commentVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    // call back
    WEAKSELF
    commentVc.sendMsgCallback = ^(NSString * _Nonnull msg) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"token"] = User_Token;
        dic[@"msg_id"] = @(0);
        dic[@"ask_id"] = weakSelf.ask_id;
        dic[@"msg"] = msg;
        [QAService addCommentWithParams:dic completion:^(BOOL success) {
            if (success) {
                [weakSelf loadData];
            } else {
                [SVProgressHUD showMessage:@"评论失败"];
            }
        }];
    };
    [self presentViewController:commentVc animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.detailInfo.msg_list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WSQuestionDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:[WSQuestionDetailCell className] forIndexPath:indexPath];
    cell.detail = self.detailInfo;
    cell.message = self.detailInfo.msg_list[indexPath.section];
    WEAKSELF
    /// 采纳
    cell.didAcceptedCallback = ^(UILabel * _Nonnull lable) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否采纳此回答?" message:@"该用户将获得您的悬赏积分" preferredStyle:UIAlertControllerStyleAlert];
        // cancle
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"不了，谢谢" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // sure
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"采纳" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            WSMessageInfo *message = weakSelf.detailInfo.msg_list[indexPath.section];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"token"] = User_Token;
            dic[@"msg_id"] = message.msg_id;
            dic[@"ask_id"] = weakSelf.ask_id;
            [QAService acceptAskWithParams:dic completion:^(BOOL success) {
                if (success) {
                    lable.hidden = NO;
                }
            }];
        }];
        [alertController addAction:cancleAction];
        [alertController addAction:sureAction];
        [self presentViewController:alertController animated:YES completion:nil];
    };
    
    /// 回复
    cell.replyCallback = ^{
        WSCommentViewController *commentVc = [[WSCommentViewController alloc] init];
        commentVc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        commentVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        // call back
        WEAKSELF
        commentVc.sendMsgCallback = ^(NSString * _Nonnull msg) {
            WSMessageInfo *message = weakSelf.detailInfo.msg_list[indexPath.section];
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            dic[@"token"] = User_Token;
            dic[@"msg_id"] = message.msg_id;
            dic[@"ask_id"] = weakSelf.ask_id;
            dic[@"msg"] = msg;
            [QAService addCommentWithParams:dic completion:^(BOOL success) {
                if (success) {
                    [weakSelf loadData];
                } else {
                    [SVProgressHUD showMessage:@"回复失败"];
                }
            }];
        };
        [self presentViewController:commentVc animated:YES completion:nil];
    };
    
    /// 点赞
    cell.didLikedCallback = ^(UIButton * _Nonnull btn, WSQuestionDetailCell * _Nonnull aCell) {
        WSMessageInfo *message = weakSelf.detailInfo.msg_list[indexPath.section];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"token"] = User_Token;
        dic[@"msg_id"] = message.msg_id;
        dic[@"ask_id"] = weakSelf.ask_id;
        [QAService askTagsWithParams:dic completion:^(BOOL success) {
            if (success) {
                message.zan += 1;
                aCell.message = message;
            }
        }];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120.f;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
